//
//  CQPictureView.swift
//  swift-weibo
//
//  Created by 陈乾 on 15/11/1.
//  Copyright © 2015年 陈乾. All rights reserved.
//
/*
0.引入模型 刷新数据
1.创建布局模式
2.注册cell
3.遵守代理 实现数据源方法
4.自定义cell

*/
import UIKit
import SDWebImage

class CQPictureView: UICollectionView {
    
    
    
    //MARK: - 属性
    
    let ID = "item"
    //微博模型数据
    var status: CQStatus? {
        didSet{
            
            //刷新数据
            self.reloadData()
        }
    }
    //MARK: - 可以计算视图的宽高
    func calculateSize() -> CGSize {
        
        //
        let itemSize = CGSizeMake(90, 90)
        //先设置为空 当有图片的时候在设置间距 只要一张也不要设置间距
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = itemSize
        //间隙
        let margin:CGFloat = 10
        //列数
        let coulm = 3
        //取出图片的数目
        let count = status!.provideURL?.count ?? 0
        if count == 0 {
            //没有图片
            return CGSizeZero
        }
        
        
        if count == 1 {
            //只有一张图片 后面会等比拉伸
            let urlStr = status!.provideURL![0].absoluteString
            var size = CGSizeMake(150, 150)
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlStr) {
                size = image.size
            }
            layout.itemSize = size
            return size
        }
        
        //多于一张就要设置间距
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        //如果四张图片
        if count == 4 {
            let width = 2 * itemSize.width + margin
            return CGSizeMake(width, width)
        }
        
        //来这里 剩下的 2 3 5 6 7 8 9
        //宽度都是设置为 3 * 90 + 2 * 10 = 290
        //行：（图片数量 + 列数-1）/列数
        //高度为 行*90 + （行-1）* 10
        
        let width:CGFloat = 290
        let row = (count + coulm - 1) / coulm
        let height: CGFloat = CGFloat(row) * itemSize.height + (CGFloat(row) - 1) * margin
        return CGSizeMake(width, height)
    }
 
    //创建流水布局模式
    private var layout = UICollectionViewFlowLayout()
    
    //MARK: - 构造方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        //通常 collectionView的代理数据源都是控制器 这里我这么设置
        dataSource = self
        //背景透明
        backgroundColor = UIColor.clearColor()
        //注册cell
        registerClass(CQPictureViewCell.self, forCellWithReuseIdentifier: ID)
        
    }
/********end、*********/
}

extension CQPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.provideURL?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ID, forIndexPath: indexPath) as! CQPictureViewCell
        
        let url = status?.provideURL![indexPath.item]
        //取出模型里面的url字符串
        cell.pictureUrl = url
        
        return cell
    }
    
    /*********end********/
}

class CQPictureViewCell: UICollectionViewCell {
    
    //MARK: - 模型属性的url
    var pictureUrl: NSURL? {
        didSet{
            if pictureUrl != nil {
                //网络加载图片数据
                imageView.sd_setImageWithURL(pictureUrl)
                
            }
        }
    }
    
    //MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        //准备UI
        prepareUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 准备UI
    private func prepareUI() {
        
        //添加子控件
        contentView.addSubview(imageView)
        //设置约束 铺满整个cell
        imageView.ff_Fill(contentView)
    }
    
    
    //MARK: - 懒加载
    private lazy var imageView: UIImageView = {
        let imageview = UIImageView()
        imageview.contentMode = UIViewContentMode.ScaleAspectFill
        imageview.clipsToBounds = true
        return imageview
        }()
}

